//
//  ZJKComposePictureView.swift
//  MicroBlog
//
//  Created by VAD on 16/4/26.
//  Copyright © 2016年 朱江坤. All rights reserved.
//

import UIKit

import SVProgressHUD

class ZJKComposePictureView: UICollectionView {
    
    // 选择图片调用的闭包
    var selectedPictureClosure: (()->())?
    
    //当前pictureView要显示的图片
    
    lazy var images: [UIImage] = []
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setupUI(){
        
        backgroundColor = UIColor.whiteColor()
        
        //注册Cell
        registerClass(ZJKComposePictureViewCell.self, forCellWithReuseIdentifier: "cell")
        
        dataSource = self
        
        delegate = self
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let margin: CGFloat = 5
        
        let itemWH = (self.frame.width - 2 * margin)/3
        
        // 设置layout的itemSize的大小
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        layout.itemSize = CGSize(width: itemWH, height: itemWH)
        
        layout.minimumInteritemSpacing = margin
        
        layout.minimumLineSpacing = margin
    }
    
    //给外界添加图片的方法
    func addImage(image: UIImage){
        
        if images.count < 9{
            
            //给图片数组添加图片
            images.append(image)
            
            //刷新数据
            reloadData()
        }else{
            SVProgressHUD.showErrorWithStatus("数量已达上限")
        }
    }

}


// MARK: -  实现代理方法

extension ZJKComposePictureView:UICollectionViewDelegate,UICollectionViewDataSource{
    
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        self.hidden = images.count == 0
        
        return images.count + ((images.count == 0 || images.count == 9) ? 0 : 1)
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! ZJKComposePictureViewCell
        //判断是不是最后一个item
        
        //如果是最后一个item,就给cell 的image赋值为nil
        if indexPath.item == images.count{
            
            cell.image = nil
            
        }else{
            
            //如果不是最后一个item,就给它赋值数组中保存的图片
            cell.image = images[indexPath.item]
        }
        
        
        //设置点击删除按钮要执行的闭包
        cell.deleteButtonClosoure = {  [weak self] in
            
            self?.images.removeAtIndex(indexPath.item)
            
            self?.reloadData()
            
        }
        
        
        return cell
    }
    
    
    //监听cell的点击事件
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        //如果点击的是最后一个item 就执行闭包
        if indexPath.item == images.count {
            
            selectedPictureClosure?()
        }
    }
}



class ZJKComposePictureViewCell: UICollectionViewCell {
    
    // 删除按钮点击要执行的闭包
    var deleteButtonClosoure: (()->())?
    
    //定义属性,并改写set方法
    var image: UIImage? {
        
        didSet{
            
            if image == nil{
                
                imageView.image = UIImage(named: "compose_pic_add")
                
                //隐藏deleteButton
                deleteButton.hidden = true
                
            }else{
                
                //显示deleteButton
                deleteButton.hidden = false
                
                imageView.image = image
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //设置UI
    private func setupUI(){
        
        // 添加imageView
        contentView.addSubview(imageView)
        contentView.addSubview(deleteButton)
        
        // 添加约束
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
        
        deleteButton.snp_makeConstraints { (make) -> Void in
            make.top.trailing.equalTo(contentView)
        }
        
    }
    
    //点击删除Button点击事件
    @objc private func deleteButtonClick(){
        
        deleteButtonClosoure?()
    }
    // MARK: - 懒加载控件
    private lazy var imageView: UIImageView = UIImageView()
    
    // 删除按钮
    private lazy var deleteButton: UIButton = {
        
        let button = UIButton()
        //给button添加点击事件
        button.addTarget(self, action: "deleteButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        //给button添加图片
        button.setImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        
        return button
    }()

}
